package com.gw.controller;

import com.gw.mapper.UtilMapper;
import com.gw.pojo.dto.AddUtilAppDTO;
import com.gw.pojo.dto.UtilPageQueryDTO;
import com.gw.pojo.entity.UtilApp;
import com.gw.pojo.vo.AddUtilAppVO;
import com.gw.result.PageResult;
import com.gw.result.Result;
import com.gw.service.UtilService;
import com.gw.utils.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


@RestController
@RequestMapping("/util")
@Slf4j
public class UtilController {

    @Autowired
    private UtilService utilService;
    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private UtilMapper utilMapper;
    /**
     * 添加工具信息
     * @param multipartFile
     * @param appName
     * @param appDesc
     * @param appUrl
     * @param appIndicateUrl
     * @return
     */
    @PostMapping("/add")
    public Result<AddUtilAppVO> addUtilApp(@RequestParam("image") MultipartFile multipartFile,
                                           @RequestParam("appName") String appName,
                                           @RequestParam("appDesc") String appDesc,
                                           @RequestParam("appUrl") String appUrl,
                                           @RequestParam("appIndicateUrl") String appIndicateUrl)
    {
        log.info("添加工具信息...{}", appName);
        //查询数据库中是否已经存在

        UtilApp utilApp1 = new UtilApp();
        utilApp1 = utilMapper.findByAppName(appName);
        if (utilApp1 != null) {
            throw new RuntimeException("重复插入工具软件信息");
        }
        //上传头像到avatar-source桶，返回url
        String url = minioUtil.upload(multipartFile, "avatar-source");
        AddUtilAppDTO addUtilAppDTO = AddUtilAppDTO.builder()
                .appName(appName)
                .appDesc(appDesc)
                .appUrl(appUrl)
                .appIndicateUrl(appIndicateUrl)
                .appImage(url)
                .build();
        utilService.add(addUtilAppDTO);

        return Result.success();
    }


    /**
     * 分页查询工具软件（工具名模糊查询）
     * @return
     */
    @GetMapping("/page")
    public Result<PageResult> pageQuery(UtilPageQueryDTO utilPageQueryDTO){
        log.info("工具软件分页查询{}", utilPageQueryDTO);
        PageResult pageResult = utilService.pageQuery(utilPageQueryDTO);

        return Result.success(pageResult);
    }

    /**
     * 删除工具类信息
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result remove(@PathVariable int id) {
        log.info("删除工具类信息id:{}", id);
        utilService.remove(id);
        return Result.success();
    }


}
